package com.shuo.initial.config.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther 烁烁
 * @date 2020/5/11 12:37
 */
@Component
public class OneFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(OneFilter.class);
    private String[] ignoreArr=new String[]{"/favicon.ico","/static"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("OneFilter-init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(isIgnore((HttpServletRequest)servletRequest)) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            log.info("OneFilter-doFilter");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        log.info("OneFilter-destroy");
    }

    /**
     * 控制过滤器不过滤的路径
     * @param request
     * @return
     */
    private boolean isIgnore(HttpServletRequest request) {
        String path=request.getRequestURI().toLowerCase();
        for(String ignore:ignoreArr) {
            if(path.contains(ignore)) {
                return true;
            }
        }
        return false;
    }
}
